import os

import requests
from PIL import Image


class ppt():
    def download(self, url):
        try:
            response = requests.get(url)
            data = response.json()

            title = data["data"]["docId"]
            pageList = data["data"]["htmlUrls"]
            path = r"e:/"
            if not os.path.exists(path):
                os.makedirs(path)

            fileList = []
            for index, page in enumerate(pageList, start=1):
                resp = requests.get(page).content
                file = f"{path}{index}.png"

                with open(file, "wb") as f:
                    f.write(resp)
                    fileList.append(file)
                    print(f"download:{index}")


            imageList = [Image.open(i).convert("RGB") for i in fileList]
            imageList[0].save(f"e:/{title}.pdf", save_all=True, append_images=imageList[1:])

            for index, page in enumerate(pageList, start=1):
                file = f"{path}{index}.png"
                os.remove(file)

            #下载成功返回True
            return True

        except Exception as e:
            #下载失败返回False
            return False

    def create_url(self, doc_id):
        url = "https://wenku.baidu.com/ndocview/readerinfo?doc_id=" + doc_id + "&docId=" + doc_id + "&type=html&clientType=100&pn=0&isFromBdSearch=0&srcRef=&rn=100&powerId=2&bizName=mainPc"
        return url

